home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_10_07
/
1007060a
< prev
next >
Wrap
Text File
|
1992-05-04
|
1KB
|
95 lines
#include "mylib.h"
#include "rational.h"
rational rational::operator-()
{
rational result(*this);
result.num = -result.num;
return result;
}
rational operator++(rational &r, int)
{
rational result(r);
r += 1;
return result;
}
rational operator--(rational &r, int)
{
rational result(r);
r -= 1;
return result;
}
rational &rational::operator+=(rational r)
{
num = num * r.denom + r.num * denom;
denom *= r.denom;
simplify();
return *this;
}
rational &rational::operator-=(rational r)
{
num = num * r.denom - r.num * denom;
denom *= r.denom;
simplify();
return *this;
}
rational &rational::operator*=(rational r)
{
num *= r.num;
denom *= r.denom;
simplify();
return *this;
}
rational &rational::operator/=(rational r)
{
num *= r.denom;
denom *= r.num;
simplify();
return *this;
}
ostream &operator<<(ostream &os, rational r)
{
return os << '(' << r.num << '/' << r.denom << ')';
}
istream &operator>>(istream &is, rational &r)
{
long n, d;
char c = 0;
if (is >> c && c == '(')
{
is >> n >> c;
if (c == '/')
is >> d >> c;
if (c != ')')
{
is.putback(c);
is.clear(ios::failbit);
}
}
else
{
is.putback(c);
is >> n;
d = 1;
}
if (is)
r = rational(n, d);
return is;
}
void rational::simplify()
{
long x = gcd(num, denom);
num /= x;
denom /= x;
}